package gov.kqqzyyy.monkey.pharmacyscreen.code.ui;

import android.annotation.SuppressLint;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.SystemClock;
import android.util.TypedValue;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;

import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SynthesizerListener;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.pharmacyscreen.R;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.CurrentVersion;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.MyStringUtil;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.PharmacyWindowBaseActivity;
import gov.kqqzyyy.monkey.pharmacyscreen.code.mytools.SpeakTool;
import gov.kqqzyyy.monkey.pharmacyscreen.code.object.Patient;

@SuppressLint("NonConstantResourceId")
public class TCMPYScreenActivity_v2 extends PharmacyWindowBaseActivity {

    @BindView(R.id.tcm_pharmacy_window_text)
    TextView mPhaWinText;
    @BindView(R.id.tcm_datetime_text)
    TextView mDateTimeText;
    @BindView(R.id.tcm_patient_gridview)
    GridView mainGridView;
    @BindView(R.id.tcm_patient_klj_gridview)
    GridView kljGridView;
    @BindView(R.id.tcm_version_text)
    TextView mVersionText;

    private String mWindowID;
    private String mPharmacyID;
    private String mWindowName;

    private CountDownTimer lagCountTimer;
    private boolean isCallWindow = false;

    private List<Patient> callList;
    private Patient callPatient;
    private Handler handler;

    private SpeakTool speakTool;
    private CallThread callThread;

    private AlertDialog.Builder callDialogBuilder;
    private AlertDialog callDialog;

    @Override
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tcmpyscreen_v2);
        ButterKnife.bind(this);
        onBindUI();
        speakTool = new SpeakTool(this);
        handler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0x29) {
                    if (callPatient != null) {
                        dismissDialong();
                        callDialogBuilder = new AlertDialog.Builder(TCMPYScreenActivity_v2.this);
                        callDialogBuilder.setMessage("请" + MyStringUtil.doFormatXH(String.valueOf(callPatient.getPDHM())) + " 号 " + callPatient.getBRXM() + " 到 " + mWindowName + " 取药");
                        callDialog = callDialogBuilder.create();
                        callDialog.show();

                        try {
                            Field mAlert = AlertDialog.class.getDeclaredField("mAlert");
                            mAlert.setAccessible(true);
                            Object mAlertController = mAlert.get(callDialog);
                            Field mMessage = Objects.requireNonNull(mAlertController).getClass().getDeclaredField("mMessageView");
                            mMessage.setAccessible(true);
                            TextView mMessageView = (TextView) mMessage.get(mAlertController);
                            Objects.requireNonNull(mMessageView).setTextSize(TypedValue.COMPLEX_UNIT_SP, 40);
                        }catch (IllegalAccessException | NoSuchFieldException e){
                            e.printStackTrace();
                        }

                    } else {
                        dismissDialong();
                    }
                }
            }
        };
    }

    private void dismissDialong() {
        if (callDialog != null && callDialog.isShowing()) {
            callDialog.dismiss();
            callDialog = null;
        }
    }

    @Override
    protected void onBindUI() {
        super.onBindUI();
        setTimeTextView(mDateTimeText);
        setMainGridView(mainGridView);
        setKljGridView(kljGridView);
        setColumnNum(4);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isCallWindow = getmSharedPreferences().getBoolean("window_of_call", false);
        String mPharmacyName = getmSharedPreferences().getString("pharmacy_name", "");
        mWindowName = getmSharedPreferences().getString("window_name", "");
        //自煎窗口（配药呼叫）
        mWindowID = getmSharedPreferences().getString("window_detail_preference", "");
        mPharmacyID = getmSharedPreferences().getString("pharmacy_preference", "");
        if (!Objects.requireNonNull(mPharmacyName).equals("") && !mWindowName.equals("")) {
            mPhaWinText.setText("自煎草药\n颗粒剂窗口");
            mPhaWinText.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
        } else {
            Toast.makeText(getApplicationContext(), "请设置药房窗口！", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (lagCountTimer != null) {
            lagCountTimer.cancel();
        }
        if (speakTool != null) {
            speakTool.destory();
        }
        stopCallThread();
    }

    private void stopCallThread() {
        if (callThread != null) {
            callThread.interrupt();
            callThread = null;
        }
    }

    @Override
    public void doSetVersion() {
        super.doSetVersion();
        String text = "版本号：" + CurrentVersion.getVerName(this);
        mVersionText.setText(text);
    }

    @Override
    public void doFlushData() {
        super.doFlushData();
        doGetPatients(Integer.parseInt(mPharmacyID), mWindowID, false);
    }

    @Override
    protected void doFilterData() {
        super.doFilterData();
        boolean isLag = false;
        List<Patient> resultList = getmResultList();
        List<Patient> showList = new ArrayList<>();
        List<Patient> kljList = new ArrayList<>();
        callList = new ArrayList<>();
        if (resultList != null) {
            for (Patient patient : resultList
            ) {
                //正在配药
//                if (patient.getPYBZ().equals("1.0") && !patient.getJHPB().equals("2.0")) {
//                if (!patient.getJHPB().equals("2.0")) {
                if (!patient.getFYBZ().equals("1.0")) {
                    if (patient.getPYBZ().equals("1.0")) {
                        if (patient.getMJBZ() == 1) {
                            kljList.add(patient);
                        } else {
                            showList.add(patient);
                        }
                    }
//                    if (patient.getFYBZ().equals("1.0")) {
                    if (patient.getPYBZ().equals("1.0") && !patient.getJHPB().equals("2.0")) {
//                        Date localDateTime = new Date(System.currentTimeMillis());
//                        localDateTime.setTime(localDateTime.getTime() + getMyApplication().getDeteDelta() - 300000);
                        try {
//                            Date date = getMyApplication().getTsdfDateTime().parse(patient.getFYRQ());
//                            if (Objects.requireNonNull(date).getTime() - localDateTime.getTime() > 0) {
                            callList.add(patient);
//                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }

            }
            setmShowList(showList);
            setKljList(kljList);
            if (callList.size() == 0 || !isCallWindow) {
                isLag = true;
                Message message1 = new Message();
                message1.what = 0x29;
                callPatient = null;
                handler.sendMessage(message1);
            } else {
//                KLog.d("APE", callList);
                doCallPatients();
            }
        } else {
            isLag = true;
        }
        if (isLag) {
            lagCountTimer = new CountDownTimer(10000, 5000) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    doFlushData();
                }
            }.start();
        }
    }

    //呼叫病人操作
    protected void doCallPatients() {
        stopCallThread();
        callThread = new CallThread();
        callThread.start();
    }

    //呼叫病人线程
    private class CallThread extends Thread {

        private boolean keepCalling = true;
        private boolean callNext = true;
        private int index = 0;

        @Override
        public void run() {
            super.run();
            while (keepCalling) {
                if (callNext) {
                    callNext = false;
                    Patient patient = callList.get(index);
                    Message message = new Message();
                    message.what = 0x29;
                    callPatient = patient;
                    handler.sendMessage(message);

                    String speakMessage = "请 " + patient.getPDHM() + " 号 " + patient.getBRXM() + " 到本窗口取药 ";
                    speakMessage += " " + speakMessage;
                    speakTool.speak(speakMessage, listener);
                    //更新
//                    doUpdateJHPB(patient);
                }
                try {
//                    Thread.sleep(1000);
                    SystemClock.sleep(1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }

        private final SynthesizerListener listener = new SynthesizerListener() {
            @Override
            public void onSpeakBegin() {
            }

            @Override
            public void onBufferProgress(int percent, int beginPos, int endPos, String info) {

            }

            @Override
            public void onSpeakPaused() {
            }

            @Override
            public void onSpeakResumed() {
            }

            @Override
            public void onSpeakProgress(int percent, int beginPos, int endPos) {

            }

            @Override
            public void onCompleted(SpeechError speechError) {
                if (index == callList.size() - 1) {
                    keepCalling = false;
                    callNext = false;
                    Message message = new Message();
                    message.what = 0x29;
                    callPatient = null;
                    handler.sendMessage(message);
                    doFlushData();
                } else {
                    index++;
                    callNext = true;
                }
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {
            }
        };

    }

    @Override
    protected void doRollingGridView() {
        super.doRollingGridView();
        rollingGridView(mainGridView, 1);
        rollingGridView(kljGridView, 1);
    }
}